/**
 * Created by ZHOUSH on 12/18/2015.
 */
var csvmap = require('../tool/csvmap.js');
var Promise = require('promise');
var pexist = Promise.denodeify(require('fs').exists);
var path = './server/file/file-map.csv';

var find = function (hash) {
    return csvmap.toObject(path).then(function (data) {
        var founds = data.filter(function (item) {
            return item.hash == hash;
        });
        return founds.length > 0 ? founds[0] : null;
    });
};

var insert = function (original, filename, hash) {
    return csvmap.toObject(path).then(function (data) {
        var ret = {};
        var found = data.filter(function (item) {
                return item.filename == filename;
            }).length > 0;
        if (!found) {
            ret = {
                time: (new Date()).getTime(),
                filename: filename,
                original: original,
                hash: hash
            };
            data.push(ret);
        } else {
            found[0].original = original;
        }
        return csvmap.toFile(data, path).then(function () {
            return ret;
        });
    });
};

var remove = function (hash) {
    return csvmap.toObject(path).then(function (data) {
        var found = data.filter(function (item) {
            return item.hash == hash;
        });
        if (found.length > 0) {
            var index = data.indexOf(found[0]);
            data.splice(index, 1);
        }
        return csvmap.toFile(data, path).then(function () {
            return found[0];
        });
    });
};

var update = function (hash) {
    return csvmap.toObject(path).then(function (data) {
        var found = data.filter(function (item) {
            return item.hash == hash;
        });
        if (found.length > 0) {
            found[0].time = (new Date()).getTime();
        }
        return csvmap.toFile(data, path).then(function () {
            return found[0];
        });
    })
};

var pexists = function (path) {
    return new Promise(function (resolve, reject) {
        require('fs').exists(path, function (there) {
            resolve(there);
        });
    });
}

var query = function (filter) {
    return csvmap.toObject(path).then(function (data) {
            return data.filter(filter)
        }).then(function (list) {
            return Promise.all(list.map(function (item) {
                return pexists('server/file/data/' + item.filename + '_DATA').then(function (there) {
                    item.data = there;
                    return item;
                })
            })).then(function (items) {
                return items;
            });
        });
};

exports.insert = insert;
exports.remove = remove;
exports.find = find;
exports.update = update;
exports.query = query;